package com.example.controller;

import com.example.mapper.MemberMapper;
import com.example.mapper.UsersMapper;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/api/members")
public class MemberController {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UsersMapper usersMapper;

    @GetMapping("/byLeader")
    public Map<String, Object> getMembersByLeader(@RequestParam String leader) {
        Map<String, Object> result = new HashMap<>();
        try {
            String membersStr = memberMapper.selectByLeader(leader);
            List<String> memberNames = new ArrayList<>();
            if (membersStr != null && !membersStr.isEmpty()) {
                memberNames = Arrays.asList(membersStr.split(","));
            }
            
            // 获取成员详细信息，包括leader自己
            List<User> members = new ArrayList<>();
            for (String username : memberNames) {
                User user = usersMapper.findByUsername(username);
                if (user != null) {
                    members.add(user);
                }
            }
            
            // 确保leader也在成员列表中
            boolean leaderIncluded = false;
            for (User user : members) {
                if (user.getUsername().equals(leader)) {
                    leaderIncluded = true;
                    break;
                }
            }
            
            // 如果leader不在成员列表中，添加leader
            if (!leaderIncluded) {
                User leaderUser = usersMapper.findByUsername(leader);
                if (leaderUser != null) {
                    members.add(leaderUser);
                }
            }
            
            result.put("code", "200");
            result.put("msg", "获取成员列表成功");
            result.put("data", members);
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "获取成员列表失败: " + e.getMessage());
        }
        return result;
    }
}